﻿#include "tabsolochat.h"
#pragma execution_character_set("utf-8")
TabSoloChat::TabSoloChat() {
    init();
    this->setStyleSheet("QWidget {"
                        "   background-color: #F5F5F5;"
                        "   border-radius: 15px;"
                        "}");
}

void TabSoloChat::init() {
    scrollArea = new QScrollArea(this);
    scrollArea->setFixedSize(300,550);
    scrollContainer = new QWidget(this);
    scrollLayout = new QVBoxLayout();
    scrollContainer->setLayout(scrollLayout);
    scrollArea->setWidget(scrollContainer);

    scrollContainer->setFixedSize(290, 500);

    chatroom = new Chatroom(Operation::SendTextMsg);
    chatroom->init();

    QHBoxLayout *hBoxLayout = new QHBoxLayout();
    hBoxLayout->addWidget(scrollArea);
    hBoxLayout->addWidget(chatroom);

    setLayout(hBoxLayout);
}

void TabSoloChat::setRecentContactList(QList<RecentContact> recentContactList) {
    this->recentContactList = recentContactList;
}

void TabSoloChat::initRecentContactList(QJsonDocument doc) {
    for (auto each: doc.object()["recent"].toArray()) {
        RecentContact tmpRecentContact;
        tmpRecentContact.id = each.toObject()["id"].toInt();
        tmpRecentContact.time = each.toObject()["time"].toString();
        tmpRecentContact.nickname = each.toObject()["name"].toString();
        tmpRecentContact.avatorPath = each.toObject()["avator"].toString();
        tmpRecentContact.shortMsg = each.toObject()["msg"].toString();
        qDebug() << tmpRecentContact.toString();
        recentContactList.append(tmpRecentContact);
    }
    generateRecentContactBoxes();
}

void TabSoloChat::generateRecentContactBoxes() {
    for(int i = 0; i < recentContactList.size(); ++i){
        RecentContactBox * box = new RecentContactBox(
                    recentContactList[i].id,
                    recentContactList[i].nickname,
                    recentContactList[i].time,
                    recentContactList[i].shortMsg,
                    recentContactList[i].avatorPath,
                    0);
        myRecentContactBoxes[recentContactList[i].id] = box;

        KeySender *keySender = new KeySender();
        keySender->setId(recentContactList[i].id);

        connect(box, SIGNAL(clicked()), keySender, SLOT(emitId()));
        connect(keySender, SIGNAL(sendId(qint32)), this, SLOT(handleBoxClicked(qint32)));
        scrollLayout->addWidget(box);
    }
    scrollLayout->addStretch();
}

void TabSoloChat::handleBoxClicked(qint32 id) {
    qDebug() << "handleBoxClicked(qint32 " << id << ")";
    chatroom->setReId(id);
    chatroom->clearMsg();
    QString path = CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/history/%1.json").arg(id);
    qDebug() <<"filepath:"<<path;
    QFile file(path);
    if ( !file.exists() ) {
        qDebug() << "文件打开失败!\n";
        QJsonArray historyArray;
        QJsonDocument doc;
        QJsonObject obj;
        obj.insert("history", historyArray);
        doc.setObject(obj);
        QFile jsonfile(path);
        jsonfile.open(QIODevice::WriteOnly);
        jsonfile.write(doc.toJson());
        jsonfile.close();
    }
    else {
        qDebug() << "文件打开成功";

        file.open(QIODevice::ReadOnly);
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(file.readAll(),&error);

        if(!doc.isNull() && error.error == QJsonParseError::NoError){
            QJsonObject jsonObject = doc.object();
            if ( jsonObject.contains( "history" ) && jsonObject.value( "history" ).isArray() ) {
                QJsonArray jsonArray = jsonObject.value( "history" ).toArray();
                for ( int i = 0; i < jsonArray.size(); i++ ) {
                    if ( jsonArray[ i ].isObject() ) {
                        QJsonObject jsonObjectPost = jsonArray[ i ].toObject();
                        if ( jsonObjectPost.contains( "senderId" ) &&
                             jsonObjectPost.contains( "type" ) &&
                             jsonObjectPost.contains( "time" ) &&
                             jsonObjectPost.contains( "data" )) {
                            //发送者为自己时
                            if( jsonObjectPost["senderId"].toInt() == CONF.userId){
                                if(jsonObjectPost.value( "type" ).toString() == "text" ||
                                   jsonObjectPost.value( "type" ).toString() == "img" ||
                                   jsonObjectPost.value( "type" ).toString() == "file"){
                                    qDebug() << "my ID" << CONF.userId;
                                    qDebug() << "sender Id" << jsonObjectPost.contains( "senderId" );
                                    MyChatItem * mychatItem = new MyChatItem();
                                    QString avatorPath = CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/soloavator/%1.jpg").arg(CONF.userId);
                                    mychatItem->setAvator(avatorPath);
                                    mychatItem->setTime(jsonObjectPost.value( "time" ).toString());
                                    if(jsonObjectPost.value( "type" ).toString() == "text"){
                                        mychatItem->setMsg(jsonObjectPost.value( "data" ).toString());

                                        myRecentContactBoxes[id]->changeTime(jsonObjectPost.value( "time" ).toString());
                                        myRecentContactBoxes[id]->changeMsg(jsonObjectPost.value( "data" ).toString());

                                    }
                                    else if(jsonObjectPost.value( "type" ).toString() == "img"){
                                        qDebug() <<"picture path ::" << CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/img/") + jsonObjectPost.value( "data" ).toString();
                                        mychatItem->addPic(CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/img/") + jsonObjectPost.value( "data" ).toString());

                                        myRecentContactBoxes[id]->changeTime(jsonObjectPost.value( "time" ).toString());
                                        myRecentContactBoxes[id]->changeMsg("A picture");
                                    }
                                    //                            TODO: 文件展示
                                    else if(jsonObjectPost.value( "type" ).toString() == "file"){
                                        myRecentContactBoxes[id]->changeTime(jsonObjectPost.value( "time" ).toString());
                                        myRecentContactBoxes[id]->changeMsg("A file");
                                    }
                                    chatroom->addNewWidget(mychatItem);
                                }

                                else if(jsonObjectPost.value( "type" ).toString() == "voice"){
                                    VoiceMsg * voiceItem = new VoiceMsg(CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId)
                                                                    + QString("/soloavator/%1.jpg").arg(CONF.userId),
                                                                    jsonObjectPost.value( "time" ).toString(),
                                                                    CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId)
                                                                    + QString("/voice/") + jsonObjectPost.value( "data" ).toString());
                                    chatroom->addNewWidget(voiceItem);
                                }
                            }
                            else{
                                ChatItem * chatItem = new ChatItem();
                                QString avatorPath = CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/soloavator/%1.jpg").arg(id);
                                chatItem->setAvator(avatorPath);
                                chatItem->setTime(jsonObjectPost.value( "time" ).toString());
                                if(jsonObjectPost.value( "type" ).toString() == "text"){
                                    chatItem->setMsg(jsonObjectPost.value( "data" ).toString());

                                    myRecentContactBoxes[id]->changeTime(jsonObjectPost.value( "time" ).toString());
                                    myRecentContactBoxes[id]->changeMsg(jsonObjectPost.value( "data" ).toString());
                                }
                                else if(jsonObjectPost.value( "type" ).toString() == "img"){
                                    qDebug() <<"picture path ::" << CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/img/") + jsonObjectPost.value( "data" ).toString();
                                    chatItem->addPic(CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/img/") + jsonObjectPost.value( "data" ).toString());

                                    myRecentContactBoxes[id]->changeTime(jsonObjectPost.value( "time" ).toString());
                                    myRecentContactBoxes[id]->changeMsg("A picture");
                                }
                                //                            TODO: 文件展示
                                else if(jsonObjectPost.value( "type" ).toString() == "file"){
                                    myRecentContactBoxes[id]->changeTime(jsonObjectPost.value( "time" ).toString());
                                    myRecentContactBoxes[id]->changeMsg("A file");
                                }
                                chatroom->addNewWidget(chatItem);
                            }

                        }
                    }
                }
            }
        }
    }
}
